--lua内存管理器
local insert = table.insert
LuaMemManager = {}
LuaMemManager.config_list = {}
LuaMemManager.__id = -999
requireConfig = false           --优化后的配置require方法
--time 是延迟卸载的时间
local LUA_TYPE = {
    VIEW = {id = "VIEW" , time = 10},
    ALWAYS = {id = "ALWAYS" , time = 10},
    CONFIG = {id = "CONFIG" , time = 10},
}

function LuaMemManager.ReSetRequire()
    originRequireFunc = _G.require
    requireConfig = function(module , name)
        LuaMemManager.NewRequire(module , name)
    end
end

function LuaMemManager.NewRequire(module , name)
    print(module , name , "加载成功")
    local vo = {
        path = module,
        time = GetTime(),
        name = name,
        type = LUA_TYPE.ALWAYS.id
    }
    LuaMemManager.config_list[vo.name] = vo
end

function LuaMemManager.LoadConfig(name)
    if LuaMemManager.config_list[name] then
        LuaMemManager.config_list[name].time = GetTime()
        return originRequireFunc(LuaMemManager.config_list[name].path)
    end
end

--定时检测销毁
function LuaMemManager.Update(time)
    local curr_time = GetTime()
    for name, vo in pairs(LuaMemManager.config_list) do
        local time = LUA_TYPE[vo.type].time or 10
        if vo.time + time <= curr_time then
            --销毁
            if package.loaded[vo.path] then
                package.loaded[vo.path] = nil
                print(vo.path , ": loaded 卸载成功")
            end
            if package.preload[vo.path] then
                package.preload[vo.path] = nil
                print(vo.path , ": preload 卸载成功")
            end
        end
    end
end


